package com.dc.juc.example._9_concurrent;

import com.dc.juc.annoations.ThreadSafe;
import com.google.common.base.Throwables;
import lombok.extern.slf4j.Slf4j;

import java.util.Set;
import java.util.concurrent.*;

/**
 * Description: 线程安全类_ConcurrentSkipListSet
 *
 *  TreeSet -> ConcurrentSkipListSet
 *
 * @author: gdc
 * @date: 2021/8/11
 * @version 1.0
 */
@ThreadSafe
@Slf4j
public class _3_ConcurrentSkipListSet {

    public static Set<Integer> SET = new ConcurrentSkipListSet<>();

    /**
     * 请求总数
     */
    public static int CLIENT_TOTAL = 5000;
    /**
     * 同时并发执行的线程数
     */
    public static int THREAD_TOTAL = 200;


    public static void main(String[] args) throws InterruptedException {
        ExecutorService threadPool = Executors.newCachedThreadPool();
        Semaphore semaphore = new Semaphore(THREAD_TOTAL);
        CountDownLatch countDownLatch = new CountDownLatch(CLIENT_TOTAL);
        for (int i = 0; i < CLIENT_TOTAL; i++) {
            int num = i;
            threadPool.execute(() -> {
                try {
                    semaphore.acquire();

                    update(num);

                    semaphore.release();
                } catch (InterruptedException e) {
                    log.error("异常信息为：{}", Throwables.getStackTraceAsString(e));
                } finally {
                    countDownLatch.countDown();
                }
            });
        }
        countDownLatch.await();
        threadPool.shutdown();

        log.info("SET length = {}", SET.size());
    }

    private static void update(int num){
        SET.add(num);
    }

}
